﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Diagnostics;


namespace HttpDownloader
{
    
    class MyDownload
    {
        private string m_pStrProxy = "";
        private string m_pStrPort = "";
        private string m_pStrUrl = "";
        private string m_pStrFilePath = "";
        private string m_pStrFileName = "";
        private string m_pStrOriginLink = "";
        string linkRequest = "";

        private bool isFailedLink = false;
        private int iNumThread = 2;

        public Int64 iTotalSizeOfFile = 0;
        public Int64 iCurrentDownloaded = 0;
        public Int64 m_pStrTransferRate = 0;
        private int iThreadFail = 0;
        public double bytesPerSecond = 0;
        private ListViewItem objListItem = new ListViewItem();
        private ListViewItem[] m_pListProcess;

        Socket client;
        DownloadProcess m_pDownloadProcess;
        SegmentThread[] segmentThread;
        private Thread[] downloadThread;
        private Thread m_pThread;

        public bool isFinishDownload = false;
        public bool isBeginDownload = false;
        private bool isStop = false;
        private bool isPause = false;

        public string m_pFileType = "";

        readonly object syncLock = new object();
        Stopwatch duration;

        List<object> lstOb = new List<object>(3);
        string[] arrItemDownload = new string[6];
        public event EventHandler OnUpdateListView;
        ListViewItem itemp;
        public ListViewItem GetSetListViewItem
        {
            get { return objListItem; }
            set
            {
                //lstOb.Remove(m_pFileType);
                //lstOb.Remove(objListItem);
                //lstOb.Remove(m_pStrFileName);
                for (int i = 0; i < lstOb.Count; i++)
                {
                    lstOb.RemoveAt(i);
                }

                this.objListItem = value;
                /*
                if(lstOb.Count > 3)
                {
                    for(int i =0; i < lstOb.Count; i++)
                    {
                        lstOb.RemoveAt(i);
                    }
                }*/
                lstOb.Insert(0, m_pStrFileName);
                lstOb.Insert(1, objListItem);
                lstOb.Insert(2, m_pFileType);
                //lstOb.Add(m_pStrFileName);
                //lstOb.Add(objListItem);
                //lstOb.Add(m_pFileType);

                if (this.OnUpdateListView != null)
                    this.OnUpdateListView(lstOb, new EventArgs());
            }
        }

        public MyDownload()
        {
            m_pDownloadProcess = new DownloadProcess();
        }

        public MyDownload(string url, string filePath, string proxy, string port, int numConnect)
        {
            m_pDownloadProcess = new DownloadProcess();
            DownloadProcess.CheckForIllegalCrossThreadCalls = false;
            m_pDownloadProcess.ShowDownloadProcess();
            m_pDownloadProcess.Show();
            m_pStrUrl = url;
            m_pStrOriginLink = url;
            m_pStrFilePath = filePath;
            m_pStrProxy = proxy;
            m_pStrPort = port;
            iNumThread = numConnect;
        }

        public string StrFilePath
        {
            get { return m_pStrFilePath; }
            set { m_pStrFilePath = value; }
        }

        public void setNumberSegment(int numberSegment)
        {
            iNumThread = numberSegment;
        }
        
        public void myHttpDownload()
        {
            byte[] requestData = new byte[1024];
            byte[] data = new byte[1024];
            int recv = 0;
            string sizeOfFile = "";
            string sttCode = "";


            string host = GetHost(m_pStrUrl);
            string address = GetIPAdress(host);

            IPEndPoint iep;
            try
            {
                if (m_pStrProxy.Equals("") || m_pStrPort.Equals(""))
                {
                    iep = new IPEndPoint(IPAddress.Parse(address), 80);
                }
                else
                {
                    iep = new IPEndPoint(IPAddress.Parse(m_pStrProxy), System.Convert.ToInt32(m_pStrPort));
                }
            }
            catch (System.Exception ex)
            {
                arrItemDownload[0] = m_pStrOriginLink;
                arrItemDownload[1] = "Error link";
                arrItemDownload[3] = sizeOfFile; arrItemDownload[2] = ""; arrItemDownload[4] = ""; arrItemDownload[5] = "" + DateTime.Now;

                itemp = new ListViewItem(arrItemDownload);
                itemp.SubItems[0].Text = m_pStrOriginLink;
                itemp.SubItems[2].Text = sizeOfFile;
                itemp.SubItems[1].Text = "Error link"; itemp.SubItems[3].Text = ""; itemp.SubItems[4].Text = ""; itemp.SubItems[5].Text = "" + DateTime.Now;
                this.GetSetListViewItem = itemp;

                MessageBox.Show("Error link");
                return;
            }
            

            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                client.Connect(iep);
            }
            catch (Exception)
            {
                arrItemDownload[0] = m_pStrOriginLink;
                arrItemDownload[1] = "Error";
                arrItemDownload[3] = sizeOfFile; arrItemDownload[2] = ""; arrItemDownload[4] = ""; arrItemDownload[5] = "" + DateTime.Now;

                itemp = new ListViewItem(arrItemDownload);
                itemp.SubItems[0].Text = m_pStrOriginLink;
                itemp.SubItems[2].Text = sizeOfFile;
                itemp.SubItems[1].Text = "Error"; itemp.SubItems[3].Text = ""; itemp.SubItems[4].Text = ""; itemp.SubItems[5].Text = "" + DateTime.Now;
                this.GetSetListViewItem = itemp;

                MessageBox.Show("Khong the ket noi den server");
                isFailedLink = true;
                client.Close();
                return;
            }

            linkRequest = m_pStrUrl.Substring(7 + host.Length);

            //gui yeu cau
            string request = "GET " + linkRequest + " HTTP/1.1\r\nHost:" + host + 
                                                             "\r\nUser_Agent: Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)"+
                                                             "\r\nCache-Control: no-cache"+
                                                             "\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"+
                                                             "\r\nAccept-Language: vi-vn,vi;q=0.8,en-us;q=0.5,en;q=0.3" +
                                                             "\r\nAccept-Encoding: gzip,deflate" +
                                                             "\r\nAccept-Charset: UTF-8,*" +
                                                             "\r\nKeep-Alive: 300"+
                                                             "\r\n\r\n";
            

            requestData = Encoding.ASCII.GetBytes(request);
            client.Send(requestData, requestData.Length, SocketFlags.None);

            //lay header
            string strHeader = "";
            string strData = "";
            string line = "";
            StringReader strReader;
            bool isHeader = true;
            while (((recv = client.Receive(data)) != 0))
            {
                strData = Encoding.ASCII.GetString(data);
                strReader = new StringReader(strData);
                while ((line = strReader.ReadLine()) != null)
                {
                    if (!line.Equals("") && (isHeader))
                    {
                        strHeader = strHeader + line + "\r\n";
                    }
                    else
                    {
                        isHeader = false;
                        break;
                    }
                }
                if (!isHeader)
                {
                    break;
                }
            }
            
            m_pStrFileName = getFileNameFromLink(m_pStrUrl);
            
            //lay gia tri tu cac method trong http header
            //lay statusCode
            sttCode = getProperties(strHeader, "HTTP");
            if (sttCode.Equals("200") || sttCode.Equals("301") || sttCode.Equals("302"))
            {
                if (sttCode.Equals("301") || sttCode.Equals("302"))
                {
                    m_pStrUrl = getProperties(strHeader, "Location");
                    m_pStrUrl = standardizedLink(m_pStrUrl);
                    myHttpDownload();
                    return;
                }
            }
            else
            {
                arrItemDownload[0] = m_pStrFileName;
                arrItemDownload[1] = "Error";
                arrItemDownload[3] = sizeOfFile; arrItemDownload[2] = ""; arrItemDownload[4] = ""; arrItemDownload[5] = "" + DateTime.Now;

                itemp = new ListViewItem(arrItemDownload);
                itemp.SubItems[0].Text = m_pStrFileName;
                itemp.SubItems[2].Text = sizeOfFile;
                itemp.SubItems[1].Text = "Error"; itemp.SubItems[3].Text = ""; itemp.SubItems[4].Text = ""; itemp.SubItems[5].Text = "" + DateTime.Now;
                this.GetSetListViewItem = itemp;       
            }

            if(m_pStrFileName.Trim().Equals(""))
            {
                isFailedLink = true;

                arrItemDownload[0] = m_pStrOriginLink;
                arrItemDownload[1] = "Error";
                arrItemDownload[3] = sizeOfFile; arrItemDownload[2] = ""; arrItemDownload[4] = ""; arrItemDownload[5] = "" + DateTime.Now;

                itemp = new ListViewItem(arrItemDownload);
                itemp.SubItems[0].Text = m_pStrOriginLink;
                itemp.SubItems[2].Text = sizeOfFile;
                itemp.SubItems[1].Text = "Error"; itemp.SubItems[3].Text = ""; itemp.SubItems[4].Text = ""; itemp.SubItems[5].Text = "" + DateTime.Now;
                this.GetSetListViewItem = itemp;
                return;
            }

            //Xu ly khi bat dc true link
            //tao file, neu gap file trung thi them fan mo rong
            int count = 1;
            string tempFileName = m_pStrFileName;
            while (File.Exists("E:\\" + tempFileName))
            {
                tempFileName = "(" + count + ")" + m_pStrFileName;
                count++;
            }
            m_pStrFileName = tempFileName;

            if (m_pStrFilePath.Equals(""))
                m_pStrFilePath = "E:\\" + tempFileName;
            m_pFileType = getTypeOfFile(m_pStrFilePath);

            arrItemDownload[0] = m_pStrFileName;
            //Xu ly kich thuoc file...
            sizeOfFile = getProperties(strHeader, "Content-Length");

            //tim kich thuoc file
            if (!sizeOfFile.Equals(""))
            {
                iTotalSizeOfFile = Convert.ToInt64(sizeOfFile);

                arrItemDownload[1] = "Connecting....";
                arrItemDownload[3] = formatSizeInByte(iTotalSizeOfFile); arrItemDownload[2] = ""; arrItemDownload[4] = ""; arrItemDownload[5] = "" + DateTime.Now;

                itemp = new ListViewItem(arrItemDownload, getImage(m_pFileType));
                itemp.SubItems[0].Text = m_pStrFileName;
                itemp.SubItems[2].Text = formatSizeInByte(iTotalSizeOfFile);
                itemp.SubItems[1].Text = "Connecting..."; itemp.SubItems[3].Text = ""; itemp.SubItems[4].Text = ""; itemp.SubItems[5].Text = "" + DateTime.Now;
                this.GetSetListViewItem = itemp;
                Thread.Sleep(300);

                string acceptRange = getProperties(strHeader, "Accept-Ranges");
                if(!acceptRange.Trim().Equals("bytes"))
                {
                    iNumThread = 1;
                }
                
                m_pDownloadProcess.setFixInfo(m_pStrUrl, iTotalSizeOfFile);
                //tao file name
                FileStream stream = new FileStream(m_pStrFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);
                stream.Close();
                //chia tung luong de gui
                m_pListProcess = new ListViewItem[iNumThread]; 
                downloadThread = new Thread[iNumThread];
                segmentThread = new SegmentThread[iNumThread];
                String[] stringRequestByteRanges = new String[iNumThread];
                int index = 0;
                Int64 iRange = 0;
                string[] text = new string[3];
                text[0] = ""; text[1] = ""; text[2] = "";
                for (index = 0; index < iNumThread; index++)
                {
                    
                    //tao luong de download luong
                    m_pListProcess[index] = new ListViewItem(text);
                    m_pDownloadProcess.addToList(m_pListProcess[index]);
                    segmentThread[index] = new SegmentThread(index, m_pStrUrl);
                    segmentThread[index].setFileName(m_pStrFilePath);
                    segmentThread[index].IOffset = (int)iRange;
                    segmentThread[index].iTotalThread = iNumThread;
                    segmentThread[index].OnReceiveData += new EventHandler(segmentThread_OnReceiveData);
                    if (index <= iNumThread - 2)
                    {
                        segmentThread[index].setRequest(linkRequest, host, iRange, (iRange + iTotalSizeOfFile / iNumThread - 1),iep);
                    }
                    else if (index == (iNumThread - 1))
                    {
                        segmentThread[index].setRequest(linkRequest, host, iRange, (iTotalSizeOfFile - 1),iep);
                    }
                    downloadThread[index] = new Thread(new ParameterizedThreadStart(segmentThread[index].DoStart));//chay thread download
                    downloadThread[index].Start(0);

                    iRange = iRange + iTotalSizeOfFile / iNumThread;
                    Thread.Sleep(100);
                }

                m_pThread = new Thread(GetCurrentDownloaded);
                m_pThread.Start();
            }
            else
            {
                arrItemDownload[1] = "Error";
                arrItemDownload[3] = "0 B"; arrItemDownload[2] = ""; arrItemDownload[4] = ""; arrItemDownload[5] = "" + DateTime.Now;

                itemp = new ListViewItem(arrItemDownload, getImage(m_pFileType));
                itemp.SubItems[0].Text = m_pStrFileName;
                itemp.SubItems[2].Text = "0 B";
                itemp.SubItems[1].Text = "Error"; itemp.SubItems[3].Text = ""; itemp.SubItems[4].Text = ""; itemp.SubItems[5].Text = "" + DateTime.Now;
                this.GetSetListViewItem = itemp;
            }
            //cai nay luon o cuoi
            client.Close();
        }

        //chuc nang bo xung cua download
        public void Resume()
        {
            if (isFailedLink || isFinishDownload) return;

            isPause = false;
            isBeginDownload = true;
            
            for (int i = 0; i < iNumThread; i++)
            {
                if (downloadThread[i] != null)
                {
                    long startPoint = 0;
                    if (File.Exists(m_pStrFilePath))
                    {
                        startPoint = segmentThread[i].ICurrentDownloaded;
                    }
                    else
                    {
                        itemp.SubItems[1].Text = "Error";
                        this.GetSetListViewItem = itemp;
                        MessageBox.Show("The file you choosed to resume doesn't exist.", "Could not resume", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;                    
                    }

                    segmentThread[i].goPause = false;
                    segmentThread[i].m_pInfo = "Downloading...";

                    downloadThread[i] = new Thread(new ParameterizedThreadStart(segmentThread[i].DoStart));//chay thread download
                    downloadThread[i].Start(startPoint);
                    Thread.Sleep(100);
                }
            }
            itemp.SubItems[1].Text = "Downloading...";
            this.GetSetListViewItem = itemp;

            m_pThread = new Thread(GetCurrentDownloaded);
            m_pThread.Start();
        }

        public void Pause()
        {
            if (isFailedLink || isFinishDownload) return;

            isPause = true;
            Thread.Sleep(100);
            for (int i = 0; i < iNumThread; i++)
            {
                if (downloadThread[i] != null)
                {                    
                    downloadThread[i].Interrupt();
                    
                    segmentThread[i].goPause = true;
                    segmentThread[i].m_pInfo = "Paused";
                    segmentThread[i].client.Close();
                    segmentThread[i].closeFile();

                    m_pListProcess[i].SubItems[0].Text = "" + i;
                    m_pListProcess[i].SubItems[1].Text = "" + formatSizeInByte(segmentThread[i].ICurrentDownloaded);
                    m_pListProcess[i].SubItems[2].Text = "" + segmentThread[i].m_pInfo;
                    m_pDownloadProcess.setThreadProcess(i, m_pListProcess[i]);

                    
                }
            }
            itemp.SubItems[1].Text = "Paused";
            this.GetSetListViewItem = itemp;

            if (m_pThread.IsAlive)
            {
                m_pThread.Interrupt();
            }
        }

        public void Stop()
        {
            if (isFailedLink || isFinishDownload) return;

            for (int i = 0; i < iNumThread; i++)
            {
                segmentThread[i].m_pInfo = "Stopped";

                m_pListProcess[i].SubItems[0].Text = "" + i;
                m_pListProcess[i].SubItems[1].Text = formatSizeInByte(segmentThread[i].ICurrentDownloaded);
                m_pListProcess[i].SubItems[2].Text = "" + segmentThread[i].m_pInfo;
                m_pDownloadProcess.setThreadProcess(i, m_pListProcess[i]);

                segmentThread[i].goPause = false;
                segmentThread[i].isFinish = true;
                segmentThread[i].isCheck = false;
            }
            isStop = true;
            m_pDownloadProcess.Close();

            itemp.SubItems[3].Text = "";
            itemp.SubItems[1].Text = "Stopped";
            this.GetSetListViewItem = itemp;
        }

        public void ShowDownloadProcess()
        {   
            m_pDownloadProcess.ShowDownloadProcess();
            m_pDownloadProcess.Show();
        }

        
        void segmentThread_OnReceiveData(object sender, EventArgs e)
        {
            if(!isBeginDownload)
            {
                duration = new Stopwatch();
                duration.Start();
                isBeginDownload = true;
            }
            SegmentThread s = (SegmentThread)sender;
            if(iCurrentDownloaded <= iTotalSizeOfFile)
            {
                iCurrentDownloaded += s.IRecvByte;
                if (iCurrentDownloaded > iTotalSizeOfFile)
                    iCurrentDownloaded = iTotalSizeOfFile;
                
                m_pDownloadProcess.setDownloaded(iCurrentDownloaded);

                if (duration.Elapsed.TotalSeconds > 0)
                    bytesPerSecond = (iCurrentDownloaded / duration.Elapsed.TotalSeconds);

                m_pDownloadProcess.setTransferRate(bytesPerSecond);
            }
            if(isFinishDownload)
            {
                iCurrentDownloaded = iTotalSizeOfFile;
                m_pDownloadProcess.setDownloaded(iCurrentDownloaded);

                duration.Stop();
            }
        }
        

        public void GetCurrentDownloaded()
        {
            int i = 0;
            int iTotalFinish=0;

            if (isPause || isStop)
            {
                return;
            }

            while (true)
            {
                if (isFinishDownload == true)
                {
                    break;
                }

                //if ((isPause && !isStop) || (isStop && isFinishDownload))
                if (isPause || isStop)
                {
                    return;
                }

                itemp.SubItems[4].Text = getByteRate(bytesPerSecond);
                itemp.SubItems[3].Text = "" + m_pDownloadProcess.strTimeLeft;
                itemp.SubItems[1].Text = "Downloading...";
                this.GetSetListViewItem = itemp;

                for(i = 0; i < iNumThread; i++)
                {
                    if (!segmentThread[i].isFinish && iCurrentDownloaded <= iTotalSizeOfFile)
                    {
                        m_pListProcess[i].SubItems[0].Text = "" + i;
                        m_pListProcess[i].SubItems[1].Text = formatSizeInByte(segmentThread[i].ICurrentDownloaded);
                        m_pListProcess[i].SubItems[2].Text = "" + segmentThread[i].m_pInfo;
                        m_pDownloadProcess.setThreadProcess(i, m_pListProcess[i]);
                        
                        if(segmentThread[i].isThreadFail)
                        {
                            iThreadFail++;  //luu so thread bi disconnect
                        }
                        segmentThread[i].iThreadFail = iThreadFail;
                    }

                    if (segmentThread[i].isFinish && !segmentThread[i].isCheck)
                    {
                        iTotalFinish++;
                        segmentThread[i].isCheck = true;
                        downloadThread[i].Interrupt();
                    }

                    if (iTotalFinish == iNumThread)
                    {
                        for (i = 0; i < iNumThread; i++)
                        {
                            m_pListProcess[i].SubItems[0].Text = "" + i;
                            m_pListProcess[i].SubItems[1].Text = formatSizeInByte(segmentThread[i].ICurrentDownloaded);
                            m_pListProcess[i].SubItems[2].Text = "Downloaded";
                            m_pDownloadProcess.setThreadProcess(i, m_pListProcess[i]);

                            segmentThread[i].closeFile();
                            downloadThread[i].Interrupt();
                            segmentThread[i].client.Close();
                        }
                        isFinishDownload = true;
                        if (!isStop)
                        {
                            m_pDownloadProcess.setDownloaded(iTotalSizeOfFile);
                            itemp.SubItems[1].Text = "Downloaded";
                            itemp.SubItems[3].Text = "";
                            itemp.SubItems[4].Text = "";
                            this.GetSetListViewItem = itemp;
                            MessageBox.Show("Download thanh cong. File duoc luu o: " + m_pStrFilePath);
                        }
                        break;
                    }
                }

                if(iCurrentDownloaded >= iTotalSizeOfFile)
                {
                    for (i = 0; i < iNumThread; i++)
                    {
                        m_pListProcess[i].SubItems[0].Text = "" + i;
                        m_pListProcess[i].SubItems[1].Text = formatSizeInByte(segmentThread[i].ICurrentDownloaded);
                        m_pListProcess[i].SubItems[2].Text = "Downloaded";
                        m_pDownloadProcess.setThreadProcess(i, m_pListProcess[i]);

                        segmentThread[i].closeFile();
                        downloadThread[i].Interrupt();
                        segmentThread[i].client.Close();
                    }
                    isFinishDownload = true;
                    if (!isStop)
                    {
                        m_pDownloadProcess.setDownloaded(iTotalSizeOfFile);
                        itemp.SubItems[1].Text = "Downloaded";
                        itemp.SubItems[3].Text = "";
                        itemp.SubItems[4].Text = "";
                        this.GetSetListViewItem = itemp;
                        MessageBox.Show("Download thanh cong. File duoc luu o: " + m_pStrFilePath);
                    }
                    break;
                }

                if (isFinishDownload == true)
                {
                    m_pThread.Interrupt();
                    break;
                }
            }
        }

        public bool getIsFinishDownload()
        {
            return isFinishDownload;
        }

        internal string GetIPAdress(string host)
        {
            try
            {
                IPHostEntry hostInfo = Dns.GetHostEntry(host);
                IPAddress[] address = hostInfo.AddressList;
                return address[0].ToString();
            }
            catch (System.Exception ex)
            {
                return "";
            }

        }

        internal string GetHost(string url)
        {
            url = url.ToLower();
            try
            {
                Uri tmp = new Uri(url);
                return tmp.Host;
            }
            catch (System.Exception ex)
            {

            }
            return "";
        }

        public string getByteRate(double byteRate)
        {
            string strByteRate = "";
            lock (syncLock)
            {
                if (byteRate > Math.Pow(2, 30))
                {
                    byteRate = byteRate / 1024;
                    strByteRate = String.Format("{0:f3} MB/s", byteRate);
                    return strByteRate;
                }
                if (bytesPerSecond > Math.Pow(2, 10))
                {
                    byteRate = byteRate / 1024;
                    strByteRate = String.Format("{0:f3} KB/s", byteRate);
                    return strByteRate;
                }
                if (bytesPerSecond < 1024)
                {
                    byteRate = byteRate / 1024;
                    strByteRate = String.Format("{0:f3} B/s", byteRate);
                    return strByteRate;
                }
                return strByteRate;
            }
        }
        //them %20 vao cac khoang cach trong link
        public string standardizedLink(string link)
        {
            string linkStandardized = link.Replace(" ", "%20");
            return linkStandardized;
        }
        //loai bo %20
        public string standardizedFileName(string filename)
        {
            string filenameStandardized = filename.Replace("%20", " ");
            return filenameStandardized;
        }

        public string getFileNameFromLink(string link)
        {
            string fname = "";
            link = link.Replace("\n", "");
            link = link.Replace("\r", "");
            string[] arr = link.Split('/');
            
            if (arr.Length > 1)
            {
                fname = arr[arr.GetLength(0) - 1];
                if (fname.Contains("?"))
                {
                    arr = fname.Split('?');
                    fname = arr[0];
                }
                
            }
            else
                fname = link;

            return fname;
        }

        public string getTypeOfFile(string filePath)
        {
            string fileType = "";
            string fname = getFileNameFromLink(filePath);
            string[] arr = fname.Split('.');
            if (arr.Length > 1)
                fileType = arr[arr.GetLength(0) - 1];
            else
                fileType = "";
            return fileType;
        }

        public string getProperties(string header, string method)
        {
            string strValue = "";
            using (StringReader reader = new StringReader(header))
            {
                string line;

                while ((line = reader.ReadLine()) != null)
                {
                    if (line.StartsWith(method, StringComparison.OrdinalIgnoreCase) == true)
                    {
                        if (!method.Equals("HTTP"))
                        {
                            strValue = line.Substring(method.Length + 2);
                        }
                        else
                            strValue = line.Substring(9, 3);
                        break;
                    }
                }
            }
            return strValue;
        }

        public int getImage(string fileType)
        {
            int index = 11;//anh mac dinh

            if (fileType.Equals("jpg") || fileType.Equals("png") || fileType.Equals("jpeg") || fileType.Equals("ico") || fileType.Equals("gif"))
            {
                //filepath += "images.png";
                index = 4;//images 
            }
            else if (fileType.Equals("doc") || fileType.Equals("docx"))
            {
                //filepath += "doc.png";
                index = 0;
            }
            else if (fileType.Equals("xls"))
            {
                //filepath += "xls.png";
                index = 13;
            }
            else if (fileType.Equals("ppt") || fileType.Equals("pptx"))
            {
                //filepath += "ppt.png";
                index = 7;
            }
            else if (fileType.Equals("wma") || fileType.Equals("wmv"))
            {
                //filepath += "wma.png";
                index = 12;
            }
            else if (fileType.Equals("pdf"))
            {
                //filepath += "pdf.png";
                index = 6;
            }
            else if (fileType.Equals("exe"))
            {
                //filepath += "exe.png";
                index = 1;
            }
            else if (fileType.Equals("xml"))
            {
                //filepath += "xml.png";
                index = 14;
            }
            else if (fileType.Equals("rar") || fileType.Equals("zip"))
            {
                //filepath += "rarZip.png";
                index = 9;
            }
            else if (fileType.Equals("mp3"))
            {
                //filepath += "mp3.png";
                index = 5;
            }
            else if (fileType.Equals("flv"))
            {
                //filepath += "flv.png";
                index = 2;
            }
            else if (fileType.Equals("html"))
            {
                //filepath += "html.png";
                index = 3;
            }
            else if (fileType.Equals("txt"))
            {
                //filepath += "txt.png";
                index = 10;
            }
            else
            {
                //filepath += "undefine.png";
                index = 11;
            }
            return index;
        }

        public string formatSizeInByte(Int64 sizeInByte)
        {
            string sizeFormat = "";
            double size = sizeInByte;
            lock (syncLock)
            {
                if (size >= Math.Pow(2, 30))
                {
                    size = size / Math.Pow(2, 30);
                    sizeFormat = String.Format("{0:f3} GB", size);
                    return sizeFormat;
                }
                if (size >= Math.Pow(2, 20))
                {
                    size = size / Math.Pow(2, 20);
                    sizeFormat = String.Format("{0:f3} MB", size);
                    return sizeFormat;
                }
                if (size >= Math.Pow(2, 10))
                {
                    size = size / Math.Pow(2, 10);
                    sizeFormat = String.Format("{0:f3} KB", size);
                    return sizeFormat;
                }
                if (size < 1024)
                {
                    sizeFormat = String.Format("{0:f3} B", sizeInByte);
                    return sizeFormat;
                }
            }
            return sizeFormat;
        }
    }
}
